package com.example.myapplication1;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import android.view.MenuItem;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {
    private BottomNavigationView bottomNav;
    private FrameLayout fragmentContainer;

    private HomeFragment homeFragment;
    private FindFragment findFragment;
    private MineFragment mineFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initFragment();
        setBottomNavListener();
    }

    private void initView() {
        bottomNav = findViewById(R.id.bottom_nav);
        fragmentContainer = findViewById(R.id.fragment_container);
    }

    private void initFragment() {
        homeFragment = new HomeFragment();
        findFragment = new FindFragment();
        mineFragment = new MineFragment();

        // 默认显示首页
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, homeFragment)
                .commit();
    }

    private void setBottomNavListener() {
        bottomNav.setOnItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.menu_home) {
                switchFragment(homeFragment);
            } else if (id == R.id.menu_find) {
                switchFragment(findFragment);
            } else if (id == R.id.menu_mine) {
                switchFragment(mineFragment);
            }
            return true;
        });
    }

    // 切换 Fragment
    private void switchFragment(Fragment targetFragment) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, targetFragment)
                .commit();
    }
}